package com.framework.util.shell;

import java.io.File;
import java.net.URL;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;

import com.framework.annotation.SystemLog;
import com.framework.entity.DatasourceFormMap;
import com.framework.util.Common;
import com.framework.util.datasource.EnvironmentFileInfo;
import com.framework.util.datasource.InvokeBatUtil;
import com.framework.util.datasource.RunsqlUtils;
import com.framework.util.datasource.SystemInfo;

/**
 * 打算，但是没写
* @author Lyon:
* @version 创建时间：2016年11月18日 上午9:29:33
* 类说明
*/
public class CreateDBBuilder {
	
	private final static Logger logger = Logger.getLogger(CreateDBBuilder.class);
	
	@SystemLog(module="createMultiDB",methods="DataclientController--createMultiDB" )
	public String createMultiDB(String db_name, String dbusername, String dbpassword, final String db_nameNext)
			throws Exception {
		
		DatasourceFormMap user = DatasourceFormMap.mapper().findDBTablesViews(db_name);
		Integer tableViewSum = user.getInt("tableViewSum");
		String result = null;
		
		if (tableViewSum!=Integer.parseInt(EnvironmentFileInfo.createdb.get("db_table_count").toString())) {
			result=caseCreate(db_name, dbusername, dbpassword);
		}else {
			DatasourceFormMap.mapper().insertPrivileges(dbusername, dbpassword);
		}
		if (EnvironmentFileInfo.createdb.get("THREAD_MODE").equals("1")) {
			DatasourceFormMap user2 = DatasourceFormMap.mapper().findDBTablesViews(db_nameNext);
			Integer tableViewSum2 = user2.getInt("tableViewSum");
			if (tableViewSum2!=Integer.parseInt(EnvironmentFileInfo.createdb.get("db_table_count").toString())) {
				String dbusernameNext=RandomStringUtils.randomAlphabetic(6);
				String dbpasswordNext=RandomStringUtils.randomAlphabetic(6);
				threadCreateDB(db_nameNext, dbusernameNext, dbpasswordNext);
			}
		}
		
		return result;
	}
	
	
	public String caseCreate(String db_name, String dbusername, String dbpassword) throws Exception {
		String result = null;
		String CREATEDB_MODE=EnvironmentFileInfo.createdb.get("CREATEDB_MODE").toString();
		if (CREATEDB_MODE.equals("1")) {
			result = createDBViaShell(db_name, dbusername, dbpassword);//
		}else if (CREATEDB_MODE.equals("2")) {
			result = createDBViaScript(db_name, dbusername, dbpassword);//
		}else {
			result = createDB(db_name, dbusername, dbpassword);//
		}
		return result;
	}
	
	public String createDB(String db_name, String dbusername, String dbpassword) throws Exception {
		final String ipaddress = EnvironmentFileInfo.createdb.getProperty("db_name");

		// 执行sql文件
		RunsqlUtils runsqlUtils = new RunsqlUtils();
		String sqlfilepath = null;
		String fileName = null;
		SystemInfo systemInfo = new SystemInfo();
		boolean flag = systemInfo.isWindows();
		String batName = null;
		String filepath = null;
		String execCommand = null;
		String url = null;
		String batFunc;
		String batBasic;

		File resourceRootPath = new File(this.getClass().getResource("/").getPath());
		System.out.println(resourceRootPath);
		if (flag) {

			sqlfilepath = EnvironmentFileInfo.sql_win.getProperty("sqlPathWin")
					+ EnvironmentFileInfo.createdb.getProperty("targetSql");
			batName = EnvironmentFileInfo.sql_win.getProperty("batPath");
			batFunc = EnvironmentFileInfo.sql_win.getProperty("batFunc");
			filepath = EnvironmentFileInfo.sql_win.getProperty("sqlPathWin") + "func.bat";
			execCommand = EnvironmentFileInfo.sql_win.getProperty("execCommond");
			batBasic = EnvironmentFileInfo.sql_win.getProperty("batBasic");

			url = "jdbc:mysql://" + EnvironmentFileInfo.jdbc.getProperty("dbPosition") + "/" + db_name;
		} else {
			sqlfilepath = EnvironmentFileInfo.sql_linux.getProperty("sqlPathLin")
					+ EnvironmentFileInfo.createdb.getProperty("targetSql");
			batName = EnvironmentFileInfo.sql_linux.getProperty("shPath");
			filepath = EnvironmentFileInfo.sql_linux.getProperty("sqlPathLin") + "func.sh";
			batFunc = EnvironmentFileInfo.sql_linux.getProperty("batFuncLin");
			batFunc = batFunc.replace("where", resourceRootPath.toString());
			execCommand = EnvironmentFileInfo.sql_linux.getProperty("execCommondLin");
			execCommand = execCommand.replace("where", resourceRootPath.toString());

			batBasic = EnvironmentFileInfo.sql_linux.getProperty("batBasicLin");

			url = "jdbc:mysql://" + EnvironmentFileInfo.jdbc.getProperty("dbPosition") + "/" + db_name;
		}
		String tagerSql = "/" + EnvironmentFileInfo.createdb.getProperty("targetSql");
		sqlfilepath = runsqlUtils.alterSql(db_name, dbusername, dbpassword, sqlfilepath, tagerSql, flag);
		if (sqlfilepath == null) {
			logger.warn("sqlfilepath"+"failed");
			return "failed";
		}

		InvokeBatUtil invokeBatUtil = InvokeBatUtil.getInvokeBatUtil();// createdb.sql
		String result = invokeBatUtil.runJavaScript2(sqlfilepath);

		String standardSql = EnvironmentFileInfo.createdb.getProperty("standardSql");
		addResourceSql(invokeBatUtil, resourceRootPath.getAbsolutePath() + "/" + standardSql, url);// basic.sql

		// 只有这个方法勉强成功了

		// 二次执行 sql，heke-lost.sql
		URL sqlPathSecondUrl = getClass().getResource("/" + EnvironmentFileInfo.createdb.getProperty("targetSqlSec"));
		String sqlPathSecond = sqlPathSecondUrl.getPath();

		addResourceSql(invokeBatUtil, sqlPathSecond, url);

		if (!result.equals("true")) {

			return "failed";
		}

		if (flag) {
			// windows 导入函数
			batFunc = batFunc.replace("heke10000", db_name);
			batFunc = batFunc.replace("where", resourceRootPath.getAbsolutePath());
			invokeBatUtil.runBatFromStr(batFunc);
			// 导入不存在的lost表单
			execCommand = execCommand.replace("heke10000", db_name);
			execCommand = execCommand.replace("where", resourceRootPath.getAbsolutePath());
			invokeBatUtil.runBatFromStr(execCommand);
			// 执行资源sql
			URL viewPath = getClass().getResource("/" + EnvironmentFileInfo.createdb.getProperty("callView"));
			String viewPathPath = viewPath.getPath();
			addResourceSql(invokeBatUtil, viewPathPath, url);
		} else {
			// Linux 导入函数
			batFunc = batFunc.replace("heke10000", db_name);
			batFunc = batFunc.replace("where", resourceRootPath.getAbsolutePath());
			invokeBatUtil.runBatFromStr(batFunc);
			String[] cmd = { "/bin/sh", "-c",
					"mysql -h115.159.118.241 -uroot -p564312221Dlj heke10000 -e 'source where/heke-func.sql'" };
			cmd[2] = batFunc;
			invokeBatUtil.runBatFromStr(cmd);
			// 导入不存在的lost表单
			execCommand = execCommand.replace("heke10000", db_name);
			execCommand = execCommand.replace("where", resourceRootPath.getAbsolutePath());
			invokeBatUtil.runBatFromStr(execCommand);

			String[] cmd2 = { "/bin/sh", "-c",
					"mysql -h115.159.118.241 -uroot -p564312221Dlj heke10000 -e 'source where/heke-lost.sql'" };
			cmd2[2] = execCommand;
			invokeBatUtil.runBatFromStr(cmd2);
			// 执行资源sql
			URL viewPath = getClass().getResource("/" + EnvironmentFileInfo.createdb.getProperty("callView"));
			String viewPathPath = viewPath.getPath();

			addResourceSql(invokeBatUtil, viewPathPath, url);
		}

		return "success";
	}
	
	/**
	 * 
	 * @author 李品良
	 * @param invokeBatUtil
	 * @param sqlpath
	 * @param username
	 * @param password
	 * @param url
	 */
	public void addResourceSql(InvokeBatUtil invokeBatUtil, String sqlpath, String url) {
		try {
			invokeBatUtil.runJavaScript2(sqlpath, url);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void threadCreateDB(String db_name, String dbusername, String dbpassword) throws Exception {
		final String idb_name=db_name;
		final String idbusername=dbusername;
		final String idbpassword=dbpassword;
		
		Thread thread=new Thread(new Runnable() {
			public void run() {
				try {
					caseCreate(idb_name, idbusername, idbpassword);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					logger.warn(e);
					e.printStackTrace();
				}
			}
		});
		thread.start();
	}
	
	public String createDBViaShell(String db_name, String dbusername, String dbpassword) throws Exception {
		final String ipaddress = EnvironmentFileInfo.createdb.getProperty("db_name");

		// 执行sql文件
		RunsqlUtils runsqlUtils = new RunsqlUtils();
		String sqlfilepath = null;
		String fileName = null;
		SystemInfo systemInfo = new SystemInfo();
		boolean flag = systemInfo.isWindows();
		String batName = null;
		String filepath = null;
		String execCommand = null;
		String url = null;
		String batFunc;
		String batBasic;

		File resourceRootPath = new File(this.getClass().getResource("/").getPath());
		System.out.println(resourceRootPath);
		if (flag) {

			sqlfilepath = EnvironmentFileInfo.sql_win.getProperty("sqlPathWin")
					+ EnvironmentFileInfo.createdb.getProperty("targetSql");
			batName = EnvironmentFileInfo.sql_win.getProperty("batPath");
			batFunc = EnvironmentFileInfo.sql_win.getProperty("batFunc");
			filepath = EnvironmentFileInfo.sql_win.getProperty("sqlPathWin") + "func.bat";
			execCommand = EnvironmentFileInfo.sql_win.getProperty("execCommond");
			batBasic = EnvironmentFileInfo.sql_win.getProperty("batBasic");

			url = "jdbc:mysql://" + EnvironmentFileInfo.jdbc.getProperty("dbPosition") + "/" + db_name;
		} else {
			sqlfilepath = EnvironmentFileInfo.sql_linux.getProperty("sqlPathLin")
					+ EnvironmentFileInfo.createdb.getProperty("targetSql");
			batName = EnvironmentFileInfo.sql_linux.getProperty("shPath");
			filepath = EnvironmentFileInfo.sql_linux.getProperty("sqlPathLin") + "func.sh";
			batFunc = EnvironmentFileInfo.sql_linux.getProperty("batFuncLin");
			batFunc = batFunc.replace("where", resourceRootPath.toString());
			execCommand = EnvironmentFileInfo.sql_linux.getProperty("execCommondLin");
			execCommand = execCommand.replace("where", resourceRootPath.toString());

			batBasic = EnvironmentFileInfo.sql_linux.getProperty("batBasicLin");

			url = "jdbc:mysql://" + EnvironmentFileInfo.jdbc.getProperty("dbPosition") + "/" + db_name;
		}
		String tagerSql = "/" + EnvironmentFileInfo.createdb.getProperty("targetSql");
		sqlfilepath = runsqlUtils.alterSql(db_name, dbusername, dbpassword, sqlfilepath, tagerSql, flag);
		if (sqlfilepath == null) {
			logger.warn("sqlfilepath"+"failed");
			return "failed";
		}

		InvokeBatUtil invokeBatUtil = InvokeBatUtil.getInvokeBatUtil();// createdb.sql
		String result = invokeBatUtil.runJavaScript2(sqlfilepath);
		

		if (!result.equals("true")) {

			return "failed";
		}

		if (flag) {
			// windows 导入log_basic.sql
			return "failed";
		} else {
			// Linux 导入log_basic.sql
			String shFilePath=EnvironmentFileInfo.sql_linux.getProperty("shFilePath");
			String content=EnvironmentFileInfo.sql_linux.getProperty("log_basic");
			
			batFunc = batFunc.replace("heke10000", db_name);
			batFunc = batFunc.replace("where", resourceRootPath.getAbsolutePath());
			String path=Common.getContextClassesPath();
			path=Common.getContextRealPath();
			content=content.replace("heke10000", db_name);
			content=content.replace("where", Common.getContextClassesPath());
			invokeBatUtil.saveShell(content);
			invokeBatUtil.runBatFromStr("sh "+shFilePath);
			return "success";
		}
		
	}
	
	
	
	
	public String createDBViaScript(String db_name, String dbusername, String dbpassword) throws Exception {
		final String ipaddress = EnvironmentFileInfo.createdb.getProperty("db_name");

		// 执行sql文件
		RunsqlUtils runsqlUtils = new RunsqlUtils();
		String sqlfilepath = null;
		String fileName = null;
		SystemInfo systemInfo = new SystemInfo();
		boolean flag = systemInfo.isWindows();
		String batName = null;
		String filepath = null;
		String execCommand = null;
		String url = null;
		String batFunc;
		String batBasic;

		File resourceRootPath = new File(this.getClass().getResource("/").getPath());
		System.out.println(resourceRootPath);
		if (flag) {

			sqlfilepath = EnvironmentFileInfo.sql_win.getProperty("sqlPathWin")
					+ EnvironmentFileInfo.createdb.getProperty("targetSql");
			batName = EnvironmentFileInfo.sql_win.getProperty("batPath");
			batFunc = EnvironmentFileInfo.sql_win.getProperty("batFunc");
			filepath = EnvironmentFileInfo.sql_win.getProperty("sqlPathWin") + "func.bat";
			execCommand = EnvironmentFileInfo.sql_win.getProperty("execCommond");
			batBasic = EnvironmentFileInfo.sql_win.getProperty("batBasic");

			url = "jdbc:mysql://" + EnvironmentFileInfo.jdbc.getProperty("dbPosition") + "/" + db_name;
		} else {
			sqlfilepath = EnvironmentFileInfo.sql_linux.getProperty("sqlPathLin")
					+ EnvironmentFileInfo.createdb.getProperty("targetSql");
			batName = EnvironmentFileInfo.sql_linux.getProperty("shPath");
			filepath = EnvironmentFileInfo.sql_linux.getProperty("sqlPathLin") + "func.sh";
			batFunc = EnvironmentFileInfo.sql_linux.getProperty("batFuncLin");
			batFunc = batFunc.replace("where", resourceRootPath.toString());
			execCommand = EnvironmentFileInfo.sql_linux.getProperty("execCommondLin");
			execCommand = execCommand.replace("where", resourceRootPath.toString());

			batBasic = EnvironmentFileInfo.sql_linux.getProperty("batBasicLin");

			url = "jdbc:mysql://" + EnvironmentFileInfo.jdbc.getProperty("dbPosition") + "/" + db_name;
		}
		String tagerSql = "/" + EnvironmentFileInfo.createdb.getProperty("targetSql");
		sqlfilepath = runsqlUtils.alterSql(db_name, dbusername, dbpassword, sqlfilepath, tagerSql, flag);
		if (sqlfilepath == null) {
			logger.warn("sqlfilepath"+"failed");
			return "failed";
		}

		InvokeBatUtil invokeBatUtil = InvokeBatUtil.getInvokeBatUtil();// createdb.sql
		String result = invokeBatUtil.runJavaScript2(sqlfilepath);
		
		String standardSql ="log_basic.sql";
		addResourceSql(invokeBatUtil, resourceRootPath.getAbsolutePath() + "/" + standardSql, url);// basic.sql
		if (!result.equals("true")) {

			return "failed";
		}

		return "success";
	}
}
